<script>
import typeApi from '@/api/basic/productType'
import productApi from '@/api/basic/product'
import specApi from '@/api/basic/productSpec'
import inStorageOrder from '@/api/outstorage'
import customerApi from '@/api/basic/customer'

export default {
  props: {
    value: {
      type: [String, Number],
      default: ''
    }
  },
  data() {
    return {
      id: 0, // 新增：出库单id
      total: 0, // 新增：出库单id
      impType: 0, // 新增：出库类型标识
      des: '', // 新增：备注描述
      selectedValue: this.value,
      selectedProductValue: this.value,
      selectedProductSpecValue: this.value,
      typeList: [{ id: 0, name: '' }],
      productList: [{ id: 0, name: '' }],
      productSpecList: [{ id: 0, name: '' }],
      productSelectSpecList: [],
      dialogVisible: false,
      inboundType: '销售出库', // 新增：出库类型
      remark: '', // 新增：备注
      tableData: [], // 新增：表格数据
      currentPage: 1, // 新增：当前页码
      pageSize: 10, // 新增：每页显示条数
      keyword: '', // 新增：关键字
      type: null, // 新增：类型
      createTimeBegin: '', // 新增：创建时间开始
      createTimeEnd: '', // 新增：创建时间结束
      orderDetails: {}, // 新增：订单详情
      productDetails: [], // 新增：产品详情
      editDialogVisible: false, // 新增：编辑弹窗可见性
      customerList: [], // 新增：客户列表
      selectedCustomerId: 0 // 新增：选中的客户ID
    }
  },
  methods: {
    add() {
      this.id = 0 // 初始化id为0，表示新增出库单
      this.impType = 0 // 初始化出库类型标识
      this.des = '' // 初始化备注描述
      this.productSelectSpecList = [] // 清空选中的产品列表
      this.dialogVisible = true
    },
    typeDialogList() {
      this.selectedProductValue = ''
      this.selectedProductSpecValue = ''
      typeApi.getList()
        .then(response => {
          this.typeList = response.data
        })
    },
    productVoList() {
      if (!this.selectedValue) {
        return
      }
      this.selectedProductSpecValue = ''
      productApi.getListByTypeId(parseInt(this.selectedValue, 10))
        .then(response => {
          this.productList = response.data
        })
    },
    productSpecVoList() {
      console.log(this.selectedProductValue)
      if (!this.selectedProductValue) {
        return
      }
      specApi.getPageList({ productId: parseInt(this.selectedProductValue, 10) })
        .then(response => {
          this.productSpecList = response.data
        })
    },
    handleSelectionChange(selection) {
      this.productSelectSpecList = selection.map(item => ({

        productId: item.id,
        name: item.name,
        code: item.code,
        color: item.color,
        volume: item.volume,
        productionTime: item.productionTime,
        limitTime: item.limitTime,
        basicPrice: item.basicPrice,
        salePrice: item.salePrice,
        productNumber: item.quantity || 0
      }))
    },
    handleDelete(index, row) {
      // 删除选中的项
      this.productSelectSpecList.splice(index, 1)

      // 找到对应的 productSpecList 项并取消选中
      const specIndex = this.productSpecList.findIndex(spec => spec.id === row.id)
      if (specIndex !== -1) {
        this.$refs.productSpecTable.toggleRowSelection(this.productSpecList[specIndex], false)
      }
    },
    customerListVoList() { // 新增：获取客户列表
      // 假设有一个获取客户列表的API接口 getCustomerList
      customerApi.getPageList(1,100)
        .then(response => {
          this.customerList = response.data.records
        })
    },
    createOatStorageOrder() {
      const ostStorageData = {
        id: this.id,
        impType: this.inboundType === '销售出库' ? 1 : this.inboundType === '采购退货' ? 2 : 3,
        des: this.remark,
        productList: this.productSelectSpecList,
        customerId: this.selectedCustomerId // 新增：客户ID
      }
      // 发送请求保存出库单数据
      if (this.id === 0) {
        inStorageOrder.createOatStorageOrder(ostStorageData)
          .then(response => {
            // 提示
            this.$message.success('操作成功')
            // 关闭弹框
            this.dialogVisible = false
            // 刷新
            this.fetchTableData()
          })
      } else {
        inStorageOrder.updateStorageOrder(ostStorageData)
          .then(response => {
            // 提示
            this.$message.success('操作成功')
            // 关闭弹框
            this.dialogVisible = false
            // 刷新
            this.fetchTableData()
          })
      }
    },
    fetchTableData() { // 修改：获取表格数据时使用查询参数
      // 假设有一个获取表格数据的API接口 getTableData
      const params = {
        keyword: this.keyword,
        type: this.type,
        createTimeBegin: this.createTimeBegin ? this.$moment(this.createTimeBegin).format('YYYY-MM-DD HH:mm:ss') : '',
        createTimeEnd: this.createTimeEnd ? this.$moment(this.createTimeEnd).format('YYYY-MM-DD HH:mm:ss') : ''
      }
      inStorageOrder.getPageList(
        this.currentPage,
        this.pageSize,
        params
      )
        .then(response => {
          this.tableData = response.data.records
          this.total = response.data.total
        })
    },
    showOrderDetails(orderId) {
      this.orderDetails = {}
      this.productDetails = []
      inStorageOrder.getOstStorage(orderId)
        .then(response => {
          this.orderDetails = response.data
          inStorageOrder.listByOstId(orderId)
            .then(productResponse => {
              this.productDetails = productResponse.data
              this.editDialogVisible = true
            })
        })
    },
    deleteOrder(orderId) {
      inStorageOrder.remove(orderId.toString())
        .then(response => {
          this.$message.success('删除成功')
          this.fetchTableData()
        })
    },
    editOrder(orderId) {
      inStorageOrder.getOstStorage(orderId)
        .then(response => {
          const order = response.data
          inStorageOrder.listByOstId(orderId)
            .then(response1 => {
              this.id = order.id
              this.inboundType = order.type === 1 ? '销售出库' : order.type === 2 ? '销售退货' : order.type === 3 ? '其他出库' : '其他出库'
              this.remark = order.des
              this.productSelectSpecList = response1.data.map(item => ({
                productId: item.outStorageProduct.productId,
                name: item.productSpecifications.name,
                code: item.productSpecifications.code,
                color: item.productSpecifications.color,
                volume: item.productSpecifications.volume,
                productionTime: item.productSpecifications.productionTime,
                limitTime: item.productSpecifications.limitTime,
                basicPrice: item.productSpecifications.basicPrice,
                salePrice: item.productSpecifications.salePrice,
                number: item.outStorageProduct.number,
                hadNumber: item.outStorageProduct.hadNumber
              }))
              this.productSpecList = response1.data.map(item => ({
                productId: item.outStorageProduct.productId,
                name: item.productSpecifications.name,
                code: item.productSpecifications.code,
                color: item.productSpecifications.color,
                volume: item.productSpecifications.volume,
                productionTime: item.productSpecifications.productionTime,
                limitTime: item.productSpecifications.limitTime,
                basicPrice: item.productSpecifications.basicPrice,
                salePrice: item.productSpecifications.salePrice,
              }))
              this.selectedCustomerId = order.customerId // 新增：设置选中的客户ID
              this.dialogVisible = true
            })
        })
    }
  },
  created() {
    this.fetchTableData()
    this.customerListVoList() // 新增：在组件创建时获取客户列表
  }
}
</script>

<template>
  <div class="app-container">
    <!-- 新增：查询工作栏 -->
    <div class="search-div">
      <el-form label-width="100px" size="small">
        <el-form-item label="关键字">
          <el-input v-model="keyword" placeholder="请输入关键字"/>
        </el-form-item>
        <el-form-item label="类型">
          <el-select v-model="type" placeholder="请选择类型">
            <el-option label="销售出库" value="1"/>
            <el-option label="采购退货" value="2"/>
            <el-option label="其他出库" value="3"/>
            <!-- 根据实际情况添加更多类型选项 -->
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间">
          <el-date-picker
            v-model="createTimeBegin"
            type="datetime"
            placeholder="开始时间"
          />
          <el-date-picker
            v-model="createTimeEnd"
            type="datetime"
            placeholder="结束时间"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="fetchTableData">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <!-- 工具条 -->
    <div class="tools-div">
      <el-button type="success" icon="el-icon-plus" size="mini" @click="add">添 加</el-button>
    </div>
    <el-table
      :data="tableData"
      stripe
      border
      style="width: 100%; margin-bottom: 20px;"
    >
      <el-table-column label="序号" width="70" align="center">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column prop="orderNo" label="订单号">
        <template slot-scope="scope">
          <el-link type="primary" @click="showOrderDetails(scope.row.id)">{{ scope.row.orderNo }}</el-link>
        </template>
      </el-table-column>
      <el-table-column prop="type" label="类型"/>
      <el-table-column prop="des" label="描述"/>
      <el-table-column prop="productNumber" label="产品数量"/>
      <el-table-column prop="hadNumber" label="已出库数量"/>
      <el-table-column label="操作" width="150">
        <template slot-scope="scope">
          <el-button size="small" @click="editOrder(scope.row.id)">修改</el-button>
          <el-button size="small" type="danger" @click="deleteOrder(scope.row.id)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      @size-change="fetchTableData"
      @current-change="fetchTableData"
      :current-page="currentPage"
      :page-sizes="[10, 20, 30, 40]"
      :page-size="pageSize"
      layout="total, sizes, prev, pager, next, jumper"
      :total="total"
    />
    <el-dialog
      :visible.sync="dialogVisible"
      fullscreen
      draggable="true"
      top="40vh"
      width="70%"
      @close="dialogVisible = false"
    >
      <div class="search-div">
        <el-form label-width="70px" size="small">
          <label><span style="color: black;font-size: 20px">新增/修改出库单</span></label>
          <el-row style="background: #20a0ff;padding: 10px;margin-top: 10px"><label><span style="color: white"
          >选择产品</span></label></el-row>
          <el-row style="margin-top: 10px">
            <label>分类</label>
            <el-select clearable style="margin-left: 10px" v-model="selectedValue" placeholder="请选择产品分类"
                       @focus="typeDialogList"
            >
              <el-option
                v-for="item in typeList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
            <label style="margin-left: 20px">产品名称</label>
            <el-select clearable style="margin-left: 10px" v-model="selectedProductValue" placeholder="请选择产品"
                       @focus="productVoList"
                       @change="productSpecVoList"
            >
              <el-option
                v-for="item in productList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-row>
          <el-row>
            <el-table
              :data="productSpecList"
              ref="productSpecTable"
              stripe
              border
              style="width: 100%;margin-top: 10px;"
              @selection-change="handleSelectionChange"
            >
              <el-table-column type="selection" width="55"/>
              <el-table-column
                label="序号"
                width="70"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="规格名称"/>
              <el-table-column prop="code" label="条码"/>
              <el-table-column prop="color" label="颜色"/>
              <el-table-column prop="volume" label="体积"/>
              <el-table-column prop="productionTime" label="生产时间"/>
              <el-table-column prop="limitTime" label="保质期"/>
              <el-table-column prop="basicPrice" label="成本价"/>
              <el-table-column prop="salePrice" label="售价"/>
            </el-table>
          </el-row>
          <el-row style="background: #20a0ff;padding: 10px;margin-top: 10px"><label><span style="color: white"
          >选中的产品</span></label></el-row>
          <el-row>
            <el-table
              :data="productSelectSpecList"
              stripe
              border
              style="width: 100%;margin-top: 10px;"
            >
              <el-table-column
                label="序号"
                width="70"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="name" label="规格名称"/>
              <el-table-column prop="code" label="条码"/>
              <el-table-column prop="color" label="颜色"/>
              <el-table-column prop="volume" label="体积"/>
              <el-table-column prop="productionTime" label="生产时间"/>
              <el-table-column prop="limitTime" label="保质期"/>
              <el-table-column prop="basicPrice" label="成本价"/>
              <el-table-column prop="salePrice" label="售价"/>
              <el-table-column label="出库数量">
                <template #default="scope">
                  <el-input v-model="scope.row.number" type="number" min="0"/>
                </template>
              </el-table-column>
              <el-table-column align="right" label="操作">
                <template #default="scope">
                  <el-button
                    size="small"
                    type="danger"
                    @click="handleDelete(scope.$index, scope.row)"
                  >
                    删除
                  </el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-row>
          <el-row style="background: #20a0ff;padding: 10px;margin-top: 10px"><label><span style="color: white">客户信息</span></label></el-row>
          <el-row style="margin-top: 10px">
            <label>客户</label>
            <el-select clearable style="margin-left: 10px" v-model="selectedCustomerId" placeholder="请选择客户">
              <el-option
                v-for="item in customerList"
                :key="item.name"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-row>
          <el-row style="margin-top: 20px;">
            <label>出库类型</label>
            <el-radio-group v-model="inboundType" style="margin-left: 10px">
              <el-radio label="销售出库" value="1">销售出库</el-radio>
              <el-radio label="采购退货" value="2">采购退货</el-radio>
              <el-radio label="其他出库" value="3">其他出库</el-radio>
            </el-radio-group>
          </el-row>
          <el-row style="margin-top: 10px;"><label>备注</label></el-row>
          <el-row style="margin-top: 10px;">
            <el-input
              v-model="remark"
              type="textarea"
              :maxlength="50"
              placeholder="请输入备注"
              show-word-limit
            />
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="createOatStorageOrder">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增：编辑弹窗 -->
    <el-dialog
      :visible.sync="editDialogVisible"
      fullscreen
      draggable="true"
      top="40vh"
      width="70%"
      @close="editDialogVisible = false"
    >
      <div class="search-div">
        <el-form label-width="70px" size="small">
          <el-row style="background: #20a0ff;padding: 10px;margin-top: 10px"><label><span style="color: white"
          >订单详情</span></label></el-row>
          <el-row style="margin-top: 10px">
            <el-form-item label="订单号">
              <el-input v-model="orderDetails.orderNo" readonly/>
            </el-form-item>
            <el-form-item label="类型">
              <el-input v-model="orderDetails.type" readonly/>
            </el-form-item>
            <el-form-item label="描述">
              <el-input v-model="orderDetails.des" readonly/>
            </el-form-item>
            <el-form-item label="产品数量">
              <el-input v-model="orderDetails.productNumber" readonly/>
            </el-form-item>
            <el-form-item label="已出库数量">
              <el-input v-model="orderDetails.hadNumber" readonly/>
            </el-form-item>
            <el-form-item label="创建时间">
              <el-input v-model="orderDetails.createTime" readonly/>
            </el-form-item>
            <el-form-item label="更新时间">
              <el-input v-model="orderDetails.updateTime" readonly/>
            </el-form-item>
          </el-row>
          <el-row style="background: #20a0ff;padding: 10px;margin-top: 10px"><label><span style="color: white"
          >产品详情</span></label></el-row>
          <el-row>
            <el-table
              :data="productDetails"
              stripe
              border
              style="width: 100%;margin-top: 10px;"
            >
              <el-table-column
                label="序号"
                width="70"
                align="center"
              >
                <template slot-scope="scope">
                  {{ scope.$index + 1 }}
                </template>
              </el-table-column>
              <el-table-column prop="outStorageProduct.number" label="数量"/>
              <el-table-column prop="outStorageProduct.hadNumber" label="已出库数量"/>
              <el-table-column prop="productSpecifications.name" label="规格名称"/>
              <el-table-column prop="productSpecifications.code" label="条码"/>
              <el-table-column prop="productSpecifications.color" label="颜色"/>
              <el-table-column prop="productSpecifications.volume" label="体积"/>
              <el-table-column prop="productSpecifications.productionTime" label="生产时间"/>
              <el-table-column prop="productSpecifications.limitTime" label="保质期"/>
            </el-table>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editDialogVisible = false">关闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
